package com.power.mock.util;


import com.bj58.spat.wredis.client.builder.ClientBuilder;
import com.bj58.spat.wredis.client.config.ClientConfig;
import com.bj58.spat.wredis.client.wjedis.JedisCloudPool;
import com.bj58.spat.wredis.client.wjedis.WJedisSentinelPool;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class WRedisUtil {

    private static final Logger logger = LoggerFactory.getLogger(WRedisUtil.class);
    public static ConcurrentMap<String, Object> jedisPools = new ConcurrentHashMap<String, Object>();
    static String appNames[] = null;
    private static Properties properties = new Properties();
    private final static String appName ;
    private final static String appKey ;

    static {
        InputStreamReader inStream = null;
        try {
            inStream = new InputStreamReader(new FileInputStream(StringValue.getPath()+ "/config/wredis.properties"), Charsets.UTF_8);
            properties.load(inStream);
        } catch (FileNotFoundException e) {
            logger.error("wredis config file doesn't exist!", e);
        } catch (IOException e) {
            logger.error("wredis config file load error", e);
        } finally {
            IOUtils.closeQuietly(inStream);
        }
        appName = properties.getProperty("appname");
        appKey = properties.getProperty("appkey");
    }

    static {
        if (StringUtils.isEmpty(appName)) {
            logger.error("wredis config file error: appname doesn't exist!");
        }
        if (StringUtils.isEmpty(appKey)) {
            logger.error("wredis config file error: appkey doesn't exist!");
        }
        appNames = appName.split(",");
        String[] appKeys = appKey.split(",");
        ClientConfig.init(StringValue.getPath()+"/config/wredis_client.xml");
        for (int i = 0; i < appKeys.length; i++) {
            if (appNames[i].endsWith("::disk")) {
                jedisPools.put(appNames[i], ClientBuilder.redisCloud(appKeys[i]).build());
            }
            if (appNames[i].endsWith("::mem")){
                jedisPools.put(appNames[i], ClientBuilder.redisSentinel(appKeys[i]).build());
            }
        }
    }

    public static RedisAdaptor getJedis(String appName) {
        Object jedisCloudPool = null;
        try {
            jedisCloudPool = jedisPools.get(appName);
            if (jedisCloudPool != null) {
                if (appName.endsWith("::disk")){
                    return new RedisAdaptor(((JedisCloudPool)jedisCloudPool).getResource());
                }
                if (appName.endsWith("::mem")){
                    return new RedisAdaptor(((WJedisSentinelPool)jedisCloudPool).getResource());
                }
                return null;
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    public static void releaseJedis(final RedisAdaptor wjedis) {
        if (wjedis != null) {
            wjedis.close();
        }
    }

    public static <T> T jedis(String appName, WJedisHandler<T> handler) {
        RedisAdaptor wjedis = null;
        try {
            wjedis = WRedisUtil.getJedis(appName);
            return handler.handler(wjedis);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (wjedis != null) {
                WRedisUtil.releaseJedis(wjedis);
            }
        }
        return null;
    }
}
